import {getMyMenu} from '@/api/sysMenu';
import Layout from '@/layout';
import store from '@/store';

export const getAsyncRouter = async function () {
  return new Promise((resolve, reject) => {
    getMyMenu().then(res => {
      let menuData = res.data.list;
      let menuList = [];
      if (menuData && menuData.length > 0) {
        menuList = generateMenuTree(menuData);
      }
      menuList.push({
        path: '*', redirect: '/404', hidden: true
      });
      resolve(menuList);
    }).catch((e) => {
      reject(e);
    });
  });
};
const generateMenuTree = (menuData, isFirstDirt) => {
  if (isFirstDirt === undefined) {
    isFirstDirt = true;
  }
  let data = [];
  if (menuData && menuData.length > 0) {
    for (let i in menuData) {
      if (menuData[i].type === 2) {
        continue;
      }
      let row = {};
      let url = menuData[i].url || '';
      let query = urlToObj(url);
      let name = url.substr(1, url.length - 1);
      // name = tranUrlToName(name)
      row.name = url;

      if (menuData[i].visible !== 1) {
        row.hidden = true;
      }
      let tempUrl = url;
      if (url) {
        tempUrl = url.split('?') || [];
        if (tempUrl && tempUrl.length > 0) {
          tempUrl = tempUrl[0];
        }
      }
      row.query = query;
      row.path = tempUrl;
      row.meta = {
        title: menuData[i].name,
        icon: menuData[i].icon,
        query: query,
        permissions: menuData[i].childBtns
      };

      // let map = new Map()
      if (menuData[i].type === 0) {
        if (isFirstDirt) {
          row.component = Layout;
        } else {
          row.component = getViews(tempUrl);
        }
        row.redirect = 'noRedirect';
      } else if (menuData[i].type === 1) {
        row.component = getViews(tempUrl);
      }
      if (menuData[i].childMenus && menuData[i].childMenus.length > 0) {
        row.children = generateMenuTree(menuData[i].childMenus, false);
      }
      row.fullPath = url;
      data.push(row);
    }
    return data;
  }
};

function getViews (path) {
  return resolve => {
    require.ensure([], (require) => {
      resolve(require('@/views' + path + '.vue'));
    });
  };
}

function urlToObj(str){
  let obj = {};
  try{
    let arr1 = str.split("?");
    let arr2 = arr1[1].split("&");
    for(let i=0 ; i < arr2.length; i++){
      let res = arr2[i].split("=");
      obj[res[0]] = res[1];
    }
  } catch (e) {
    return obj;
  }
  return obj;
}

function tranUrlToName(url) {
  return url.replace(/(^|-|\/)(\w)/g,(m,$1,$2)=>$2.toUpperCase());
}

function isUrl(str) {
  var RegUrl = new RegExp();
  RegUrl.compile("^bai[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&?/.=]+$");
  if (!RegUrl.test(str)) {
    return false;
  }
  return true;
}

export function getTreeObjByValue (value, treeData, childrenKey,  valueKey, defaultObj) {
  let obj = defaultObj;
  return rec(value, treeData, childrenKey, valueKey);
  function rec (value, treeData, childrenKey, valueKey) {
    if (!treeData) return null;
    for (let i = 0; i < treeData.length; i ++) {
      if (treeData[i][valueKey] == value) {
        obj = treeData[i];
        break;
      }
      if (treeData[i][childrenKey] && treeData[i][childrenKey].length > 0) {
        rec(value, treeData[i][childrenKey], childrenKey,  valueKey);
      }
    }
    return obj;
  }
}

export function findRouteByFullPath(fullPath, routes) {
  if (routes === undefined) {
    routes = store.state.permission.routes;
  }
  let obj = null;
  return rec(fullPath, routes);
  function rec (_fullPath, _routes) {
    if (!_routes) return null;
    for (let i = 0; i < _routes.length; i ++) {
      if (_routes[i].fullPath == _fullPath) {
        obj = _routes[i];
        break;
      }
      if (_routes[i].children && _routes[i].children.length > 0) {
        rec(_fullPath, _routes[i].children);
      }
    }
    return obj;
  }
}
